package com.liyueheng.app.dataWarehouseDetail

import com.liyueheng.util.{ConfigLoader, SparkConf}
import org.apache.spark.sql.functions._

object Top10FrequentBuyers {
  def top10(): Unit = {
    println("------------------ 分析购买频次前10名用户 -----------------")
    val appName = ConfigLoader.getString("app.name")
    val databaseDwd = ConfigLoader.getString("databases.dwd")
    val databaseDws = ConfigLoader.getString("databases.dws")
    val spark = SparkConf.createSparkSession(appName)

    try {
      val actDF = spark.table(s"$databaseDwd.user_act")

      val resultDF = actDF
        .filter(col("act_type") === 2)
        .groupBy("user")
        .agg(count("user").alias("value"))
        .withColumnRenamed("user", "name")
        .orderBy(col("value").desc)
        .limit(10)

      // 保存为 dws.detail_top10_frequent_buyers
      resultDF.write.mode("overwrite").format("hive").saveAsTable(s"$databaseDws.detail_top10_frequent_buyers")

    } finally {
      SparkConf.stopSparkSession(spark)
    }
  }
}
